package com.group5.controller;

import com.group5.dao.*;
import com.group5.dao.CompanyDrugInformationMapper;
import com.group5.dao.PlatformMapper;
import com.group5.dao.UserssMapper;
import com.group5.pojo.*;
import com.group5.service.BooleanToJsonService;
import com.group5.service.OrderService;
import com.group5.service.UserssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    UserssMapper userssMapper;
    @Autowired
    PlatformMapper platformMapper;
    @Autowired
    PurchasePlanMapper purchasePlanMapper;
    @Autowired
    PurchaseListMapper purchaseListMapper;
    @Autowired
    CompanyDrugInformationMapper companyDrugInformationMapper;
    @Autowired
    DrugInfoMapper drugInfoMapper;

    UserssService userssService = new UserssService();

    OrderService orderService=new OrderService();

    BooleanToJsonService booleanToJsonService = new BooleanToJsonService();

    /**
     * 查询库存是否足够购买条目购买
     * @param purchaseList
     * @return
     */
    public boolean updateDrugUpdateStoreNum (PurchaseList purchaseList){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(purchaseList.getOrder_id());
        if(purchasePlan==null){
            return false;
        }
        PurchaseList oldPurchaseList = purchaseListMapper.selectByPrimaryKey(purchaseList.getOrder_id(),purchaseList.getDrug_id());
        CompanyDrugInformationExample companyDrugInformationExample = new CompanyDrugInformationExample();
        companyDrugInformationExample.createCriteria().andOid_sellerEqualTo(purchasePlan.getSeller_oid()).
                andDrug_idEqualTo(purchaseList.getDrug_id());
        List<CompanyDrugInformation> companyDrugInformationList = companyDrugInformationMapper.selectByExample(companyDrugInformationExample);
        if(companyDrugInformationList.isEmpty()){
            return false;
        }

        //库存不足
        if(oldPurchaseList.getPurchase_num() + companyDrugInformationList.get(0).getStore_num() <= purchaseList.getPurchase_num()){
            return false;
        }
        //库存足够，更新库存
        companyDrugInformationList.get(0).setStore_num(oldPurchaseList.getPurchase_num() + companyDrugInformationList.get(0).getStore_num() - purchaseList.getPurchase_num());
        companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformationList.get(0));
        return true;

    }

    /**
     * 草稿阶段，点击提交时，用于更新库存
     * @param purchaseList
     * @return
     */
    public int insertDrugUpdateStoreNum(PurchaseList purchaseList){
        PurchasePlan purchasePlan=purchasePlanMapper.selectByPrimaryKey(purchaseList.getOrder_id());
        CompanyDrugInformation companyDrugInformation= companyDrugInformationMapper.selectByExample(orderService.selectCompanyDrugByOidAndDrug_id(purchasePlan.getSeller_oid(), purchaseList.getDrug_id())).get(0);
        companyDrugInformation.setStore_num(companyDrugInformation.getStore_num()-purchaseList.getPurchase_num());
        return companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformation);
    }

    /**
     * 草稿阶段，点击提交时，判断库存是否足够
     * @param purchaseList
     * @return
     */
    public boolean checkInsertDrugStoreNum(PurchaseList purchaseList){
        PurchasePlan purchasePlan=purchasePlanMapper.selectByPrimaryKey(purchaseList.getOrder_id());
        CompanyDrugInformation companyDrugInformation= companyDrugInformationMapper.selectByExample(orderService.selectCompanyDrugByOidAndDrug_id(purchasePlan.getSeller_oid(), purchaseList.getDrug_id())).get(0);
        return companyDrugInformation.getStore_num() >= purchaseList.getPurchase_num();
    }
    /**
     * 删除list时更新库存用
     * @param order_id
     * @param drug_id
     * @return
     */
    public boolean deleteDrugUpdateStoreNum ( int order_id, int drug_id) {
        PurchaseList purchaseList = purchaseListMapper.selectByPrimaryKey(order_id,drug_id);
        PurchasePlanExample purchasePlanExample=new PurchasePlanExample();
        purchasePlanExample.createCriteria().andOrder_idEqualTo(purchaseList.getOrder_id());
        List<PurchasePlan> purchasePlanList = purchasePlanMapper.selectByExample(purchasePlanExample);
        if(purchasePlanList.isEmpty()){
            return false;
        }
        CompanyDrugInformationExample companyDrugInformationExample = new CompanyDrugInformationExample();
        companyDrugInformationExample.createCriteria().andOid_sellerEqualTo(purchasePlanList.get(0).getSeller_oid()).
                andDrug_idEqualTo(purchaseList.getDrug_id());
        List<CompanyDrugInformation> companyDrugInformationList = companyDrugInformationMapper.selectByExample(companyDrugInformationExample);
        if(companyDrugInformationList.isEmpty()){
            return false;
        }
        companyDrugInformationList.get(0).setStore_num( companyDrugInformationList.get(0).getStore_num() + purchaseList.getPurchase_num());
        companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformationList.get(0));
        return true;
    }

    /**
     * 卖方员工查询他所在的组的购买计划，给出用户名，返回购买计划列表
     * @param username
     * @return List<PurchasePlan>
     */
    @GetMapping("/sellerQueryHisGroupPurchasePlan")//todo:
    public List<PurchasePlan> sellerQueryHisGroupPurchasePlan(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return purchasePlanMapper.sellerQueryHisGroupPurchasePlan(list.get(0).getUid());
    }

    @GetMapping("/buyerQueryPurchasePlanHaveQuotedPrice")//3,查询卖方打回的订单
    public List<PurchasePlan>buyerQueryPurchasePlanHaveQuotedPrice(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        List<PurchasePlan> planList= purchasePlanMapper.selectByExample(orderService.buyerQueryPurchasePlan(list.get(0).getOid(),3));
        planList.addAll(purchasePlanMapper.selectByExample(orderService.buyerQueryPurchasePlan(list.get(0).getOid(),7)));
        return planList;
    }
    @GetMapping("/buyerQueryPurchasePlanDraft")//1，草稿
    public List<PurchasePlan>buyerQueryPurchasePlanDraft(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return purchasePlanMapper.selectByExample(orderService.buyerQueryPurchasePlan(list.get(0).getOid(),1));
    }
    @GetMapping("/allHistoricalOrders")
    public List<PurchasePlan> allHistoricalOrders(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return purchasePlanMapper.selectByExample(orderService.buyerQueryPurchasePlan(list.get(0).getOid(),4));
    }
    /**
     * 给出orderid，返回这个订单的列表
     * @param order_id
     * @return List<PurchaseList>
     */
    @GetMapping("/QueryPurchaseListByOrderID")
    public List<PurchaseList> sellerQueryPurchaseListByOrderID(@RequestParam Integer order_id) {
         return purchaseListMapper.selectByExample(orderService.sellerQueryPurchaseListByOrderIDService(order_id));
    }
    /**
     * 给出一个买方用户名，返回与他有关联的卖方列表
     * @param username
     * @return
     */
    @GetMapping("/buyerQueryAvailableSeller")
    public List<Platform> buyerQueryAvailableSeller(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return platformMapper.buyerQueryAvailableSeller(list.get(0).getOid());
    }


    /**
     * 买方操作员创建一个订单，买方操作员先选取一个卖方机构，然后展示卖方可以卖的药，买方操作员选择药品、数量、扣率，最后选择为保存草稿或者提交。
     * 前端传入参数为一个json的数组，其中objects[0]为卖方机构的oid，objects[1]为买方操作员的username ，objects[2]为一个字符串，"1"为提交"、0"为草稿，随后是一串purchase_list
     * 首先需要把所有的objects[index]转化为json，然后使用fastJson将json转化为对应的对象。
     * 根据buyerUsername找到买方机构oid,根据seller_oid、买方机构oid、state、和两个时间信息制作purchase_plan，存到数据库中。
     * 根据两个oid和Order_time找到数据库的表项，目的是查到数据库为该purchase_plan分配的order_id 。
     * 最后，遍历每一个purchase_list,分配order_id,并添加到数据库中。
     *
     * @param objects
     * @return
     */

    @PostMapping("/buyerCreatePlan")
    public int buyerCreatePlan(@RequestBody Object[] objects) {

        int seller_oid = orderService.getSellerOidByObject(objects[0]);
        String buyerUsername = orderService.getBuyerAdminUsernameByObject(objects[1]);
        String state = orderService.getStateByObject(objects[2]);
        List<PurchaseList> purchaseLists = new ArrayList<>();
        for (int PurchanseListNum = 0; PurchanseListNum < objects.length - 3; PurchanseListNum++) {
            purchaseLists.add(orderService.getPurchaseListByObject(objects[PurchanseListNum + 3]));
        }
        PurchasePlan purchasePlan = new PurchasePlan();
        Userss userss = userssMapper.selectByExample(orderService.selectUserByUsername(buyerUsername)).get(0);
        purchasePlan.setBuyer_oid(userss.getOid());
        purchasePlan.setSeller_oid(seller_oid);
        if (state.equals("1"))
            purchasePlan.setList_status(2);
        else purchasePlan.setList_status(1);
        String OrderTime = orderService.getTime();
        purchasePlan.setOrder_time(OrderTime);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.insert(purchasePlan);
        //下一步的目的是获取数据库为purchasePlan分配的order_id
        PurchasePlan purchasePlan1 = purchasePlanMapper.selectByExample(orderService.selectPurchaseBySellerAndBuyerAndOrderTime(seller_oid, userss.getOid(), OrderTime)).get(0);
//        for (PurchaseList purchaseList : purchaseLists) {
//            purchaseList.setOrder_id(purchasePlan1.getOrder_id());
//            purchaseList.setGuide_wholesale_price(1.1);
//            purchaseList.setUnit_price(companyDrugInformationMapper.selectByExample(orderService.selectDrugByOidAndDrugid(seller_oid, purchaseList.getDrug_id())).get(0).getUnit_price());
//            purchaseListMapper.insert(purchaseList);
//
//            CompanyDrugInformation companyDrugInformation=companyDrugInformationMapper.selectByExample(orderService.selectCompanyDrugByOidAndDrug_id(purchasePlan1.getSeller_oid(),purchaseList.getDrug_id())).get(0);
//            companyDrugInformation.setStore_num(companyDrugInformation.getStore_num()-purchaseList.getPurchase_num());
//            companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformation);
//        }
        //提交订单，把库存减掉
        if(purchasePlan.getList_status()==2){
            for (PurchaseList purchaseList : purchaseLists) {
                purchaseList.setOrder_id(purchasePlan1.getOrder_id());
                purchaseList.setGuide_wholesale_price(1.1);
                purchaseList.setDrug_name(drugInfoMapper.selectByPrimaryKey(purchaseList.getDrug_id()).getDrug_name());
                purchaseList.setUnit_price(companyDrugInformationMapper.selectByExample(orderService.selectDrugByOidAndDrugid(seller_oid, purchaseList.getDrug_id())).get(0).getUnit_price());
                purchaseListMapper.insert(purchaseList);

                CompanyDrugInformation companyDrugInformation=companyDrugInformationMapper.selectByExample(orderService.selectCompanyDrugByOidAndDrug_id(purchasePlan1.getSeller_oid(),purchaseList.getDrug_id())).get(0);
                companyDrugInformation.setStore_num(companyDrugInformation.getStore_num()-purchaseList.getPurchase_num());
                companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformation);
            }
        }
        //保存为草稿，不改库存
        else{
            for (PurchaseList purchaseList : purchaseLists) {
                purchaseList.setOrder_id(purchasePlan1.getOrder_id());
                purchaseList.setGuide_wholesale_price(1.1);
                purchaseList.setDrug_name(drugInfoMapper.selectByPrimaryKey(purchaseList.getDrug_id()).getDrug_name());
                purchaseList.setUnit_price(companyDrugInformationMapper.selectByExample(orderService.selectDrugByOidAndDrugid(seller_oid, purchaseList.getDrug_id())).get(0).getUnit_price());
                purchaseListMapper.insert(purchaseList);
            }
        }
        return 1;
    }
    @GetMapping("/buyerQueryOneSellerDrug")
    public List<CompanyDrugInformation> buyerQueryOneSellerDrug(@RequestParam Integer oid){
        return companyDrugInformationMapper.
                selectByExample(orderService.buyerQueryOneSellerDrugExample(oid));
    }



    /**
     * 买方操作员对草稿进行添加阶段，向前端发送该订单中还未添加的药品。
     * 前端传参数为订单号order_id,首先根据订单号查卖方机构oid。
     * 具体的逻辑是，查询卖方机构的药，查询该订单的药，然后取他们的差集
     *
     * @param order_id
     * @return
     */
    @GetMapping("/UnselectedDrugs")
    public List<CompanyDrugInformation> UnselectedDrugs(@RequestParam Integer order_id){
        int oid=purchasePlanMapper.selectByPrimaryKey(order_id).getSeller_oid();
        return companyDrugInformationMapper.UnselectedDrugsBySeller_oidAndOrder_id(oid,order_id);
    }

    /**
     * 买方操作药员在草稿阶段添加药品，前端给操作员展示草稿中未选择的药品，操作员进行选择，然后前端把这些药品发给后端。
     * 传参数为List<PurchaseList>，代表一串药品订单，每一个PurchaseList前端已经写好的项有：order_id,drug_id,purchase_num,discount,drug_name
     * @param purchaseLists
     * @return
     */

    @PostMapping("/insertListForPlan")
    public int insertListForPlan(@RequestBody List<PurchaseList> purchaseLists){
        int seller_oid=purchasePlanMapper.selectByPrimaryKey(purchaseLists.get(0).getOrder_id()).getSeller_oid();
        int insertNum=0;
        for(PurchaseList purchaseList:purchaseLists){
            purchaseList.setUnit_price(companyDrugInformationMapper.selectByExample
                    (orderService.selectDrugByOidAndDrugid(seller_oid, purchaseList.getDrug_id())).get(0).getUnit_price());
            purchaseList.setGuide_wholesale_price(1.1);
            purchaseList.setDrug_name(drugInfoMapper.selectByPrimaryKey(purchaseList.getDrug_id()).getDrug_name());
            insertNum+=purchaseListMapper.insert(purchaseList);

            //TODO：减库存
            CompanyDrugInformation companyDrugInformation=companyDrugInformationMapper.selectByExample(orderService.selectCompanyDrugByOidAndDrug_id(seller_oid,purchaseList.getDrug_id())).get(0);
            companyDrugInformation.setStore_num(companyDrugInformation.getStore_num()-purchaseList.getPurchase_num());
            companyDrugInformationMapper.updateByPrimaryKey(companyDrugInformation);
        }
        return insertNum;
    }

    /**
     * 买方删除未生效的采购计划，物理删除给定order_id的所有list和plan。
     * @param order_id
     * @return
     */

    @DeleteMapping("/deletePlanAndLists")
    public int deletePlanAndLists(@RequestParam Integer order_id) {
        List<PurchaseList> purchaseLists=purchaseListMapper.selectByExample(orderService.selectPurchaseListByOrder_id(order_id));
        for(PurchaseList purchaseList:purchaseLists){
            if(deleteDrugUpdateStoreNum(order_id,purchaseList.getDrug_id()))
                purchaseListMapper.deleteByPrimaryKey(order_id,purchaseList.getDrug_id());
        }
        return purchasePlanMapper.deleteByPrimaryKey(order_id);
    }

    /**
     * 买方审核采购计划阶段，买方删除一个list条目，物理删除。
     * 传参数为要删除的PurchaseList，取出其中的主键进行删除。
     * @param
     * @return
     */
    @DeleteMapping("/deleteList")
    public int deleteList(@RequestParam int order_id,@RequestParam int drug_id){
        if(deleteDrugUpdateStoreNum(order_id,drug_id))
            return purchaseListMapper.deleteByPrimaryKey(order_id,drug_id);
        return 0;
    }

    /**
     * 删除一个list并上买方锁（7）
     * @param order_id
     * @param drug_id
     * @return
     */
    @DeleteMapping("/deleteListAndLock")
    public int deleteListAndLock(@RequestParam int order_id, @RequestParam int drug_id){
        deleteDrugUpdateStoreNum(order_id,drug_id);
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
        purchasePlan.setList_status(7);
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        if(deleteDrugUpdateStoreNum(order_id,drug_id))
            return purchaseListMapper.deleteByPrimaryKey(order_id,drug_id);
        return 0;
    }

    /**
     * 收取orderID
     * 买方提交采购计划,根据orderID更新purchaseplan表中plan的状态（2：提交状态）
     * 返回2
     * @param order_id
     * @return
     */
    @GetMapping("/buyerCommitPlan")
    public int buyerCommitPlan(@RequestParam Integer order_id){
       PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
       List<PurchaseList> purchaseLists=purchaseListMapper.selectByExample(orderService.selectPurchaseListByOrder_id(order_id));
       boolean isStoreNumEnough=true;
       for(PurchaseList purchaseList:purchaseLists){
           isStoreNumEnough=checkInsertDrugStoreNum(purchaseList);
       }
       if(isStoreNumEnough){
           for(PurchaseList purchaseList:purchaseLists){
               System.out.println("更新了库存");
               insertDrugUpdateStoreNum(purchaseList);
           }
           purchasePlan.setList_status(2);
           purchasePlan.setUpdate_time(orderService.getTime());
           purchasePlanMapper.updateByPrimaryKey(purchasePlan);
           return 2;
       }
       return -1;

    }


    /**
     * 收取orderID，买方同意采购计划，修改plan的时间和状态（5：买方已确认）
     * 返回5
     * @param order_id
     * @return
     */
    @PutMapping("/buyerAgreePlan")//done
    public BooleanToJsonService buyerAgreePlan(@RequestParam Integer order_id){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
        if(7 == purchasePlan.getList_status()){
            booleanToJsonService.setCheck(false);
            return booleanToJsonService;
        }
        purchasePlan.setList_status(4);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        booleanToJsonService.setCheck(true);
        return booleanToJsonService;
    }


    /**
     *收取orderID，买方再次提交，更改plan的时间和状态(此时状态改为2,重新设为提交状态)
     * 返回0
     * @param order_id
     * @return
     */
    @PutMapping("/buyerDiscontinuePlan")//done
    public int buyerDiscontinuePlan(@RequestParam Integer order_id){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
        purchasePlan.setList_status(2);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        return 0;
    }

    /**
     * 收取orderID，卖方同意采购计划，更改plan的时间和状态（3：卖方已确认）
     * 返回6
     * @param order_id
     * @return
     */
    @PutMapping("/sellerAgreePlan")//done
    public BooleanToJsonService sellerAgreePlan(@RequestParam Integer order_id){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
        if(8 == purchasePlan.getList_status()){
            booleanToJsonService.setCheck(false);
            return booleanToJsonService;
        }
        purchasePlan.setList_status(3);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        booleanToJsonService.setCheck(true);
        return booleanToJsonService;
    }

    @PutMapping("/sellerRefusePlan")//done
    public BooleanToJsonService sellerRefusePlan(@RequestParam Integer order_id){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(order_id);
        purchasePlan.setList_status(3);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        booleanToJsonService.setCheck(true);
        return booleanToJsonService;
    }



    /**
     *收取orderID，卖方删除（中止）采购计划，更改plan的时间和状态(0：中止、拒绝)
     * 返回0
     * @param oid
     * @return
     */
    @GetMapping("/sellerDiscontinuePlan")
    public int sellerDiscontinuePlan(@RequestParam Integer oid){
        PurchasePlan purchasePlan = purchasePlanMapper.selectByPrimaryKey(oid);
        purchasePlan.setList_status(0);
        purchasePlan.setUpdate_time(orderService.getTime());
        purchasePlanMapper.updateByPrimaryKey(purchasePlan);
        return 0;
    }

    /**
     *草稿阶段编辑订单，不更新库存。
     * @param purchaseList
     */
    @PutMapping("/editlist")
    public int editList(@RequestBody PurchaseList purchaseList) {
        return purchaseListMapper.updateByPrimaryKeySelective(purchaseList);
    }




    @PutMapping("/editListAndLock")
    public BooleanToJsonService editListAndLock(@RequestBody PurchaseList purchaseList) {
        PurchasePlan purchasePlan= new PurchasePlan();
        booleanToJsonService.setCheck(updateDrugUpdateStoreNum(purchaseList));
        if(booleanToJsonService.isCheck()){
            purchasePlan.setOrder_id(purchaseList.getOrder_id());
            purchasePlan.setList_status(7);//上锁
            purchasePlanMapper.updateByPrimaryKeySelective(purchasePlan);
            purchaseListMapper.updateByPrimaryKeySelective(purchaseList);
        }
        return booleanToJsonService;
    }

    @PutMapping("SellerEditListAndLock")
    public int SellerEditListAndLock(@RequestBody PurchaseList purchaseList) {
        PurchasePlan purchasePlan= new PurchasePlan();
        purchasePlan.setOrder_id(purchaseList.getOrder_id());
        purchasePlan.setList_status(8);//上锁
        purchasePlanMapper.updateByPrimaryKeySelective(purchasePlan);
        return purchaseListMapper.updateByPrimaryKeySelective(purchaseList);
    }
}
